package com.chengzhi.eshopinventory.service.impl;

import com.alibaba.fastjson.JSON;
import com.chengzhi.eshopinventory.entity.Inventory;
import com.chengzhi.eshopinventory.mapper.InventoryMapper;
import com.chengzhi.eshopinventory.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description 库存操作
 * @author: ruanchengzhi
 * @create: 2021-04-01 17:15
 **/
@Service
public class InventoryServiceImpl implements InventoryService {

    private static final String INVENTORY_KEY = "inventory";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    private InventoryMapper inventoryMapper;

    @Override
    public Inventory getRedisInventory(Long inventoryId) {
        if (redisTemplate.hasKey(INVENTORY_KEY)) {
            HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
            if (hash.hasKey(INVENTORY_KEY, inventoryId.toString())) {
                return JSON.parseObject(JSON.toJSONString(hash.get(INVENTORY_KEY, inventoryId.toString())), Inventory.class);
            }
        }
        return null;
    }

    @Override
    public void saveRedisInventory(Inventory inventory) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.putIfAbsent(INVENTORY_KEY, inventory.getId().toString(), inventory);
    }

    @Override
    public void removeRedisInventory(Inventory inventory) {
        if (redisTemplate.hasKey(INVENTORY_KEY)) {
            HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
            if (hash.hasKey(INVENTORY_KEY, inventory.getId().toString())) {
                hash.delete(INVENTORY_KEY, inventory.getId().toString());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateInventory(Inventory inventory) {
        return this.inventoryMapper.updateById(inventory);
    }

    @Override
    public Inventory getInventoryById(Long inventoryId) {
        return inventoryMapper.queryById(inventoryId);
    }
}
